//
//  MMMDetailVC.m
//  ZZLC
//
//  Created by 杨春至 on 2017/12/13.
//  Copyright © 2017年 ZhongZeng. All rights reserved.
//

#import "MMMDetailVC.h"
#import "InvestVC.h"
#import "MMDetailHeadview.h"
#import "MMRuleView.h"
#import "MMSecurityView.h"
#import "MMExtraVC.h"
#import "CoverView.h"
#import "CounterView.h"
#import "ZZLCLoginVC.h"

typedef NS_ENUM(NSInteger,ScrolleType){
    TOP_SCROLLVIEW_TYPE,
    BOTTOMSCROLLVIEW_TYPE
};


@interface MMMDetailVC ()<UIScrollViewDelegate>{
    ScrolleType _Stype;
    BOOL _isDraggingWay;
    CounterView *_count;
    CoverView *_cover;
}
@property (nonatomic,strong) MMExtraVC *extraVC;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) MMDetailHeadview *headView;
@property (nonatomic,strong) MMRuleView *ruleView;
@property (nonatomic,strong) MMSecurityView *securView;
@property (nonatomic,strong) UILabel *scrollInfoLb;
@property (nonatomic,strong) UIImageView *counterBtn;
@property (nonatomic,strong) UIButton *startmmBtn;
@property (nonatomic,strong) ProDetailModel *model;
@property (nonatomic,assign) NSInteger productStatus;
@property (nonatomic,assign) BOOL logFlag;;
//已经投资信息
@property (nonatomic,strong) NSDictionary *mmDict;
@end

@implementation MMMDetailVC
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.title = @"新手专享No.1132";
    [self configUI];
    if (@available(iOS 11.0, *)) {
        _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
//    [self loadData];
}
- (void)loadData{
//    huoqService/Product/indexRecommend
    if (_pId) {
        [NetWorkingManager postWithRequestUrl:@"getProductById" AndParameters:@{@"parameters":[@{@"productId":self.pId} DataTOjsonStringAndAddVersion]} AndRequestBlock:^(NSDictionary *responseObject) {
            NSLog(@"%@",responseObject.DataTOjsonString);
            self.model = [ProDetailModel mj_objectWithKeyValues:[responseObject objectForKey:@"obj"]];
            if (_model) {
                [self configUIByData];
            }
            self.extraVC.infoArray = [[responseObject objectForKey:@"obj"] objectForKey:@"newInfo"];
            self.extraVC.imArray = [[responseObject objectForKey:@"obj"] objectForKey:@"infoImg"];
            self.productStatus = [[[responseObject objectForKey:@"obj"] objectForKey:@"productStatus"] integerValue];
            self.extraVC.productId = _pId;
            self.title = [[responseObject objectForKey:@"obj"] objectForKey:@"title"] ;
        } FailBlock:^(NSDictionary *errDic) {
            
        }];
    }

    BOOL isLogin = [UserModel isLogin];
    if (isLogin) {
//        User/showMyAccount
        NSDictionary *param = @{@"authorization":[UserModel authorization]};
        [NetWorkingManager postWithRequestUrl:@"User/showMyAccount" AndParameters:@{@"parameters":[param DataTOjsonStringAndAddVersion]} AndRequestBlock:^(NSDictionary *responseObject) {
            _logFlag = YES;
            self.mmDict = [responseObject objectForKey:@"obj"];
            NSLog(@"%@",responseObject);
        } FailBlock:^(NSDictionary *errDic) {
            if ([errDic[@"sate"] isEqualToString:@"noLogin"]) {
                _logFlag = NO;
            }
        }];
    }else{
        _logFlag = NO;
    }

}
- (void)configUI{
    [self.view addSubview:self.scrollView];
    [self.view addSubview:self.counterBtn];
    [self.view addSubview:self.startmmBtn];
    [_scrollView addSubview:self.headView];
    [_scrollView addSubview:self.ruleView];
    [_scrollView addSubview:self.securView];
    [_scrollView addSubview:self.scrollInfoLb];
    self.title = _model.title;
    [self addChildViewController:self.extraVC];
    [_scrollView addSubview:_extraVC.view];
    _Stype = TOP_SCROLLVIEW_TYPE;
}
- (void)configUIByData{
    _headView.model = self.model;
    _ruleView.model = self.model;
    _securView.model = self.model;
}
- (void)gotoMM{
    if (_logFlag) {
        if ([_mmDict[@"buyFreshmanProduct"] isEqualToString:@"1"]&&[self.model.productType isEqualToString:@"1"]) {
            [QMUITips showError:@"您已经买过新手产品,不可重复购买" inView:self.view hideAfterDelay:1.8];
        }else{
            InvestVC *inVC = [[InvestVC alloc]init];
            inVC.mmDataDict = self.mmDict;
            inVC.hasVerif_flag = [_mmDict[@"isBindBank"] boolValue];
            inVC.model = _model;
            [self.navigationController pushViewController:inVC animated:YES];
        }
    }else{
        [self jumpToLogVC];
    }
}
- (void)showCalcu{
    if (!_cover) {
        UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
        _count = [[CounterView alloc]initWithBlock:^{
                  [self hideCover];
        }];
        _cover = [[CoverView alloc]initWithHidenBlock:^{
      
        }];
        [window addSubview:_cover];
        [window addSubview:_count];
    }
    if (_model) {
        [_count setCalculateProVider:[_model.annualEarnings floatValue] days:[_model.lcqx integerValue]];
    }
    [self layCoverView];
    
    [self showCal];
}
- (void)layCoverView{
     UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    _count.frame = CGRectMake(0, 0, KWidth-(30), 150);
    _count.centerX = KWidth/2;
    _count.centerY = - 150;
    [_cover mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(window);
    }];
}
- (void)showCal{
     UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    _cover.alpha = 0.4;
    [UIView animateWithDuration:0.8 animations:^{
        _count.center = window.center;
    } completion:^(BOOL finished) {
        [_count setFirstRespond];
    }];
}
- (void)hideCover{
    
    _cover.alpha = 0.0;
    [UIView animateWithDuration:0.8 animations:^{
        _count.centerY = -160;
    } completion:^(BOOL finished) {
      
    }];
}
#pragma mark ----- ScrollView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (_Stype == BOTTOMSCROLLVIEW_TYPE) {
        scrollView.contentSize = CGSizeMake(KWidth,  _scrollInfoLb.bottom+60+KHeight);
        [scrollView setContentOffset:CGPointMake(0, _scrollInfoLb.bottom+60) animated:NO];
        scrollView.scrollEnabled = NO;
    }

}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y+scrollView.height>=_scrollInfoLb.bottom+40&&_Stype == TOP_SCROLLVIEW_TYPE) {
        scrollView.contentSize = CGSizeMake(KWidth,  _scrollInfoLb.bottom+60+KHeight);
        [scrollView setContentOffset:CGPointMake(0, _scrollInfoLb.bottom+60) animated:YES];
        scrollView.scrollEnabled = NO;
        _Stype = BOTTOMSCROLLVIEW_TYPE;
    }else{
        [scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    }
}
- (void)viewDidLayoutSubviews{
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 45, 0));
    }];
    [_counterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(_scrollView.mas_bottom);
        make.bottom.equalTo(self.view);
        make.width.equalTo(_counterBtn.mas_height);
    }];
    [_startmmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_counterBtn.mas_right);
        make.right.equalTo(self.view);
        make.top.equalTo(_scrollView.mas_bottom);
        make.bottom.equalTo(self.view);
    }];
 
    [_headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_scrollView);
        make.left.equalTo(_scrollView);
        make.width.equalTo(_scrollView);
        make.height.mas_greaterThanOrEqualTo(200);
    }];
    [_ruleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_headView.mas_bottom);
        make.left.equalTo(_headView);
        make.width.equalTo(_scrollView);
        make.height.mas_greaterThanOrEqualTo(180);
    }];
    [_securView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_ruleView.mas_bottom).offset(10);
        make.left.equalTo(_headView);
        make.width.equalTo(_scrollView);
        make.height.mas_greaterThanOrEqualTo(160);
    }];
    [_scrollInfoLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_securView.mas_bottom);
        make.left.equalTo(_headView);
        make.width.equalTo(_scrollView);
        make.height.mas_greaterThanOrEqualTo(78/2);
    }];
    [_extraVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_scrollInfoLb.mas_bottom).offset(60);
        make.left.equalTo(_headView);
        make.width.equalTo(_scrollView);
        make.height.equalTo(self.view.mas_height).offset(-44);
    }];
    if (_scrollInfoLb.bottom<=KHeight) {
        _scrollView.contentSize = CGSizeMake(KWidth,KHeight);
    }else{
        _scrollView.contentSize = CGSizeMake(KWidth, _scrollInfoLb.bottom);
    }
}
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [UIScrollView new];
        _scrollView.backgroundColor = RGBCOLOR(245, 245, 245);
        _scrollView.contentSize = CGSizeMake(KWidth, KHeight*2);
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.delegate = self;
        _scrollView.userInteractionEnabled = YES;
        _scrollView.bounces = NO;
    }
    return _scrollView;
}
- (MMDetailHeadview *)headView{
    if (!_headView) {
        NSArray *array = [[NSBundle mainBundle]loadNibNamed:@"MMDetailHeadview" owner:nil options:nil];
        _headView = array.firstObject;
    }
    return _headView;
}
- (MMRuleView *)ruleView{
    if (!_ruleView) {
        _ruleView = [[MMRuleView alloc]init];
        _ruleView.backgroundColor = [UIColor whiteColor];
    }
    return _ruleView;
}
- (MMSecurityView *)securView{
    if (!_securView) {
        _securView = [[MMSecurityView alloc]init];
    }
    return _securView;
}
- (UILabel *)scrollInfoLb{
    if (!_scrollInfoLb) {
        _scrollInfoLb = [UILabel new];
        _scrollInfoLb.textColor = RGBCOLOR(197, 197, 197);
        _scrollInfoLb.font = [UIFont systemFontOfSize:12];
        _scrollInfoLb.text = @"-------------------  上滑显示更多内容  -------------------";
        _scrollInfoLb.textAlignment = NSTextAlignmentCenter;
    }
    return _scrollInfoLb;
}
- (UIImageView *)counterBtn{
    if (!_counterBtn) {
        _counterBtn = [[UIImageView alloc]init];
        _counterBtn.image = UIImageMake(@"countericon");
        _counterBtn.backgroundColor = [UIColor redColor];
        _counterBtn.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showCalcu)];
        [_counterBtn addGestureRecognizer:tap];
    }
    return _counterBtn;
}
- (UIButton *)startmmBtn{
    if (!_startmmBtn) {
        _startmmBtn = [[UIButton alloc]init];
        [_startmmBtn setBackgroundImage:UIImageMake(@"bottombtnbgcolor") forState:UIControlStateNormal];
        [_startmmBtn setTitle:@"立 即 投 资" forState:UIControlStateNormal];
        [_startmmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _startmmBtn.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        [_startmmBtn bk_addEventHandler:^(id sender) {
            [self gotoMM];
        } forControlEvents:UIControlEventTouchUpInside];
    }
    return _startmmBtn;
}
- (MMExtraVC *)extraVC{
    if (!_extraVC) {
        _extraVC = [[MMExtraVC alloc]init];
        __block MMMDetailVC * weakSelf = (id)self;
        _extraVC.block = ^{
            _Stype = TOP_SCROLLVIEW_TYPE;
            [weakSelf viewDidLayoutSubviews];
//            [_scrollView setContentOffset:CGPointMake(0,0) animated:YES];
            [UIView animateWithDuration:0.1 animations:^{
                weakSelf.scrollView.contentOffset = CGPointMake(0,0);
            }];
            weakSelf.scrollView.scrollEnabled = YES;
        };
    }
  
    return _extraVC;
}
- (void)setProductStatus:(NSInteger)productStatus{
    _productStatus = productStatus;
    if (_productStatus !=0) {
        _counterBtn.userInteractionEnabled = NO;
        _startmmBtn.userInteractionEnabled = NO;
        _counterBtn.image = [UIImageMake(@"countericon") qmui_imageWithTintColor:RGBCOLOR(217, 217, 217)];
        [_startmmBtn setBackgroundImage:[UIImageMake(@"bottombtnbgcolor") qmui_imageWithTintColor:RGBCOLOR(217, 217, 217)]  forState:UIControlStateNormal];
        [_startmmBtn setTitle:@"已 售 罄" forState:UIControlStateNormal];
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}


@end
